//
//  LWPictureSelectorController.swift
//  Microblog
//
//  Created by Roman on 17/1/16.
//  Copyright © 2017年 Roman. All rights reserved.
//

import UIKit

private let picSelectorCellID = "picSelectorCellId"
//设置布局约束
let selectorCellMargin: CGFloat = 4
private let colCount: CGFloat = 3
let selectoritemWidth: CGFloat = (ScreenWidth - (colCount + 1) * selectorCellMargin) / colCount


//最大可添加的图片的张数
private let maxImageCount = 4

class LWPictureSelectorController: UICollectionViewController {
    
    //懒加载存储图片的数组
    lazy var images = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.register(LWPictureSelectorCell.self, forCellWithReuseIdentifier: picSelectorCellID)

        
    }
    /// MARK: UICollectionViewDataSource

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        //判断,如果是最后有个 则不加 1 
        let counts = images.count == maxImageCount ? 0 : 1
        
        return images.count + counts
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: picSelectorCellID, for: indexPath) as! LWPictureSelectorCell
    
        cell.backgroundColor =  UIColor.randomColor
        //给按钮设置图片
        if indexPath.item == images.count {
            //最后一个cell
            print("最后一个cell")
            cell.image = nil
        }else {
            //不是最后一个
            let image = self.images[indexPath.item]
            cell.image = image
        }
        //代理对象
        cell.delegte = self
        
        return cell
    }
}

//实现下面代理的协议方法
extension LWPictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("取消啦")
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        let image = (info[UIImagePickerControllerOriginalImage] as! UIImage).scaleImage(width: 600)

        //images.append(image)
        //添加到数组中
        images.append(image)
        collectionView?.reloadData()
        //一旦获取了协议方法后,需要程序员手动miss
        self.dismiss(animated: true, completion: nil)
        
    }
}


//遵守协议实现协议方法
extension LWPictureSelectorController: LWPictureSelectorDelegate {
    func userWillAddPic() {
       // print("+")
       //1.使用图片选择器来添加图片
        let picker = UIImagePickerController()
        ///图片是否可以被编辑
       //picker.allowsEditing = true
        //2.显示被添加的图片
        //2.1设置代理对象,实现协议方法,在协议中获取图片对象.
        picker.delegate = self
        //弹出图片选择器对象
        present(picker, animated: true, completion: nil)
    }
    func userWillDeletePic(cell:LWPictureSelectorCell) {
        print("-")
        //定义用户点击的cell 对象
        
        //根据cell对象确定用户点击的cell对应indexpath
       let indexPath =  collectionView?.indexPath(for: cell)
        //根据indexPath删除数组中对应的图片对象
        images.remove(at: indexPath!.item)
        //刷新
        collectionView?.reloadData()
        self.view.isHidden = (images.count == 0)
    }
}


///定义协议 来实现按钮的监听
@objc protocol LWPictureSelectorDelegate: NSObjectProtocol {
    //定义协议的方法
    @objc optional func  userWillAddPic()
    
    @objc optional func  userWillDeletePic(cell:LWPictureSelectorCell)
    
}


/// MARK 创建自定义cell的类
class LWPictureSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            //设置按钮的图片
            addBtn.setImage(image, for: .normal)
            //隐藏按钮
            deleteBtn.isHidden = image == nil
        }
    }
    
    //代理对象,弱引用
    weak var delegte: LWPictureSelectorDelegate?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView)
        }
        deleteBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
        //添加按钮的监听事件
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        deleteBtn.addTarget(self, action: #selector(deleteBtnDidClick), for: .touchUpInside)
        
        //修改按钮的显示模式
        addBtn.imageView?.contentMode = .scaleAspectFill
        
    
    }
    //按钮点击事件
    @objc private func addBtnDidClick() {
                //判断image对象是否为nil
        if image != nil {
            print("已经有图片了")
            return
        }
        delegte?.userWillAddPic?()

    }
    
    @objc private func deleteBtnDidClick() {
        delegte?.userWillDeletePic?(cell: self)
    }
    
    //懒加载
    lazy var addBtn: UIButton = UIButton(backImageName: "compose_pic_add", text: "", fontSize: 0, textColor: UIColor.black)
    
    lazy var deleteBtn: UIButton = UIButton(backImageName: "compose_photo_close", text: "", fontSize: 0, textColor: UIColor.black)
    
}









